package com.diandi.signature.database;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 *
 */

public class DataSourceAspect {
	private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);
	public void before(JoinPoint point) throws Throwable {
		Object target = point.getTarget();
		String method = point.getSignature().getName();
		Class<?>[] classz = target.getClass().getInterfaces();

		Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		try {
			if(null == classz || classz.length <= 0){
				return ;
			}
			Method m = classz[0].getMethod(method, parameterTypes);
			if (m != null && m.isAnnotationPresent(DataSourceRouting.class)) {
				DataSourceRouting data = m.getAnnotation(DataSourceRouting.class);
				System.out.printf(data.dbkey());
				DynamicDataSourceHolder.putDataSource(data.dbkey());
			} else {
				//所有以 find,get,list,count,query,select 开头的方法都从slave库读数据
				if (method.startsWith("find") || method.startsWith("get") || method.startsWith("list")
						|| method.startsWith("count") || method.startsWith("query") || method.startsWith("select")
						|| method.startsWith("search")) {
					DynamicDataSourceHolder.putDataSource(DbKey.SLAVE);
				} else {
					DynamicDataSourceHolder.putDataSource(DbKey.MASTER);
				}
			}

		} catch (Exception e) {
			logger.error("DataSourceAspect 异常{}", e.getMessage(), e);
		}
	}
}
